import time

from library import respberrypi, lcd1602

# 32位的数据，前16位代表湿度和后16位温度，然后每16位数的前八位和后八位分别代表小数点前后
# DHT11是一款有已校准数字信号输出的温湿度传感器。 其精度湿度+-5%RH， 温度+-2℃，量程湿度20-90%RH， 温度0~50℃
DATA_PIN = 4


def get_temperature_and_humidity():
    # 设置GPIO接口为写入数据模式
    respberrypi.gpio_init_out_channel([[DATA_PIN, respberrypi.SIG_LOW]])

    # 输出一个低电平信号
    respberrypi.gpio_output(DATA_PIN, respberrypi.SIG_LOW)

    time.sleep(0.02)
    # 0.02秒后输出一个高电平信号，启动模块测量
    respberrypi.gpio_output(DATA_PIN, respberrypi.SIG_HIGH)

    # 设置GPIO接口为读取读取数据模式
    respberrypi.gpio_init_in_channel([DATA_PIN])

    # 等待，获取到高电平信号
    while respberrypi.gpio_input(DATA_PIN) == respberrypi.SIG_LOW:
        continue

    # 等待，获取到低电平信号
    while respberrypi.gpio_input(DATA_PIN) == respberrypi.SIG_HIGH:
        continue

    data = []
    # 获取到高底电平信号后，开始读取模块获取数据
    j = 0
    while j < 40:
        k = 0
        while respberrypi.gpio_input(DATA_PIN) == respberrypi.SIG_LOW:
            continue
        while respberrypi.gpio_input(DATA_PIN) == respberrypi.SIG_HIGH:
            k += 1
            if k > 100:
                break

        if k < 10:
            data.append(0)
        else:
            data.append(1)
        j += 1

    return get_temperature(data), get_humidity(data)


def get_temperature(data):
    return get_data(data[16:24], data[24:32])


def get_humidity(data):
    return get_data(data[0:8], data[8:16])


def get_data(integer_part_bit, point_part_bit):
    integer_part = 0
    point_part = 0
    for i in range(8):
        integer_part += integer_part_bit[i] * 2 ** (7 - i)  # 转换成十进制数据
        point_part += point_part_bit[i] * 2 ** (7 - i)
    return str(integer_part) + "." + str(point_part)


if __name__ == '__main__':
    respberrypi.gpio_init()

    lcd_addr = 0x27
    i2c_port = 1
    my_lcd = lcd1602.LCD(lcd_addr, i2c_port)
    my_lcd.lcd_clear()

    while True:
        temperature, humidity = get_temperature_and_humidity()
        my_lcd.lcd_display_string("T:" + temperature, line=1, pos=5)
        my_lcd.lcd_display_string("H:" + humidity, line=2, pos=5)
        time.sleep(5)
        my_lcd.lcd_clear()